#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import pygit2
import subprocess
from ...._plugin import KernelAddonPlugin


class Plugin(KernelAddonPlugin):

    __url = "mirror://github/medusalix/xone"

    __driverFile = "1cd6a87c-623f-4407-a52d-c31be49e925c_e19f60808bdcbfbd3c3df6be3e71ffc52e43261e.cab"

    def sync(self, context):
        context.distfiles_git_clone_or_update(self.__url)

    def list_versions(self, context):
        localFullfn = context.distfiles_git_get("xone")
        return [pygit2.Repository(localFullfn).head.peel(pygit2.Commit).hex]

    def list_distfiles(self, context):
        return [context.distfiles_git_fn("xone")]

    def fetch(self, context):
        driver_url = 'http://download.windowsupdate.com/c/msdownload/update/driver/drvs/2017/07/%s' % (self.__driverFile)
        firmware_hash_algo = "sha256"
        firmware_hash = '65736a84ff4036645b8f8ec602bed91ab6353019c9cb3233decab9feec0f6f04'

        for version in context.versions:
            context.distfiles_git_clone_or_update(self.__url, commit_or_tag=version)
            context.distfiles_download(driver_url, checksum_algorithm=firmware_hash_algo, checksum=firmware_hash)

    def unpack(self, context):
        context.distfiles_git_use("xone", commit_or_tag=context.version)
        subprocess.check_call(["cabextract", "-F", "FW_ACC_00U.bin", context.distfiles_get(self.__driverFile)])

    def modify_kernel_config(self, context):
        context.select_by_symbol("JOYSTICK_XPAD", "n")
        context.select_by_symbol("MT76x2U", "n")

    def install(self, context):
        os.rename("Kbuild", "Makefile")
        with open("Makefile", "a") as f:
            f.write("\n")
            f.write("default: modules\n")
            f.write("install: modules_install\n")
            f.write("\n")
            f.write("modules modules_install clean:\n")
            f.write("        $(MAKE) -C %s/build M=%s $@\n" % (context.get_boot_entry().kernel_modules_dirpath, os.getcwd()))

        # we'd better use make with shell=True because make is too old, for example it may not use os working directory but reads bash $PWD
        makeOpts = context.get_build_variable("MAKEOPTS")
        subprocess.check_call("make %s" % (makeOpts), shell=True)
        subprocess.check_call("make %s install" % (makeOpts), shell=True)

        context.install_firmware("FW_ACC_00U.bin", "xow_dongle.bin")
